package com.product.system.controller;

import com.product.system.config.Contrast;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

@RestController
public class ActivitiController {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @PostConstruct
    public void init(){
        try {
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(Contrast.QING_JIA).singleResult();
            if (null==processDefinition){
                InputStream inputStream_xml = new ClassPathResource("/process/qingjia.bpmn20.xml").getInputStream();
                InputStream inputStream_png = new ClassPathResource("/process/qingjia.png").getInputStream();
                repositoryService
                        .createDeployment()
                        .name("请假流程")
                        .addInputStream("qingjiaxml",inputStream_xml)
                        .addInputStream("qingjiapng",inputStream_png)
                        .deploy();
            }else {
                System.out.println("流程实例已经部署完毕");
            }
        }catch (IOException e){
            System.out.println(e.getMessage());
        }

    }

    //启动一个实例（肯定会产生一个任务）
    @RequestMapping("/start")
    public void start(){
        //启动实例
        HashMap<String, Object> map = new HashMap<>();
        map.put("name1","zhangsan");
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(Contrast.QING_JIA, map);
        System.out.println(instance.getId());
    }

}
